package com.example.springboot.security.config;

import com.example.springboot.security.service.UserServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @desc
 * @Author wangsh
 * @date 2018/6/14 22:17
 */
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	public void configure(WebSecurity web) throws Exception {
		super.configure(web);
	}


	/**
	 * 请求拦截：
	 *
	 * @param http
	 * @throws Exception
	 */
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		//1.请求匹配权限
		http.authorizeRequests()//
				//4.其他所有权限需要认证后才能访问
				.anyRequest().hasAnyAuthority()//4
				.and()
				.formLogin()
				.loginPage("/login")
				.failureUrl("/login?error")
				.permitAll()
				.and()
				.logout().permitAll();
	}


	@Deprecated
	private void getauthorizeRequests(HttpSecurity http) throws Exception {
		//1.请求匹配权限
		http.authorizeRequests()//
				//2.请求匹配到/admin/**路径，并且具有ROLE_ADMIN角色用户可以访问
				.antMatchers("/admin/**").hasRole("ROLE_ADMIN")//2
				//3.请求匹配到/user/**路径，并且具有UROLE_ADMIN,ROLE_USER角色用户可以访问
				.antMatchers("/user/**").hasAnyRole("ROLE_ADMIN", "ROLE_USER")//3
				//4.其他所有权限需要认证后才能访问
				.anyRequest().hasAnyAuthority();//4
	}


	@Bean
	public UserServiceImpl getUserServiceImpl() {
		return new UserServiceImpl();
	}

	/**
	 * 重新该方式，实现自定义权限过滤,注入权限service
	 *
	 * @param auth
	 * @throws Exception
	 */
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(getUserServiceImpl());
	}
}
